package com.example.shiro.realm;

import com.example.shiro.bean.Admin;
import com.example.shiro.bean.SysPermission;
import com.example.shiro.bean.SysRole;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * Copyright(C), 2020-2021, AmbroseCdMeng
 * FileName:    LoginRealm
 * Author:      AmbroseCdMeng
 * Date:        2021/2/25 9:28
 * Description: 自定义 realm 继承 AuthorizingRealm 重写授权方法，进行授权配置
 * History:
 * <author>     <time>      <version>       <desc>
 * 作者姓名     修改时间        版本号           描述
 */
public class LoginRealm extends AuthorizingRealm {
    /**
     * 权限配置
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 拿到用户信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Admin adminInfo = (Admin) principals.getPrimaryPrincipal();
        for (SysRole role : adminInfo.getRoleList()) {
            // 将角色放入 SimpleAuthorizationInfo
            info.addRole(role.getRole());
            // 用户拥有的权限
            for (SysPermission p : role.getPermissions()){
                info.addStringPermission(p.getPermission());
            }
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取用户输入的账号
        String username = (String) authenticationToken.getPrincipal();
        System.out.println(authenticationToken.getCredentials());

        // 通过 username 从数据库中查找 User 对象
        // Shiro 有时间间隔机制，两分钟内不会重复执行该方法
        // 获取用户信息
//        Admin adminInfo = adminDao.findByUsername(username);
        Admin adminInfo = new Admin();
        if (adminInfo == null)
            return null;
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                adminInfo,
                adminInfo.getPassword(),
                ByteSource.Util.bytes(adminInfo.getSalt()),
                getName());
        return info;
    }
}
